package com.hadoop.project.entity.constant;

import com.hadoop.project.entity.hbase.*;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Alexmaodali
 * @usage:大数据计算预处理关键类
 */
public class PreProcessingDataModifier {

    public static final Boolean needResolve = true;

    /**
     * 处理字段的函数
     *
     * @param element
     * @param fieldName
     * @param <T>
     */
    public static <T> void resolveField(T element, String fieldName) {
        try {
            // 获取对象的类类型
            Class<?> clazz = element.getClass();
            // 获取指定名称的字段
            Field field = clazz.getDeclaredField(fieldName);
            // 设置可访问性，以便可以访问私有字段
            field.setAccessible(true);
            // 获取字段值
            String value = (String) field.get(element);
            // 分割字符串
            String[] parts = value.split("-");
            // 设置新值
            field.set(element, parts.length > 1 ? parts[1] : "");
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static HBaseResult preProcessingData(HBaseResult hBaseResult) {
        List<Tab> tabList = hBaseResult.getTabList().stream().filter(e -> e.getTid() != null).map(tab -> {
            resolveField(tab, "tid");
            return tab;
        }).collect(Collectors.toList());
        List<HBaseUser> hBaseUserList = hBaseResult.getHBaseUserList().stream().filter(e -> e.getUid() != null).map(user -> {
            resolveField(user, "uid");
            resolveField(user, "nickName");
            return user;
        }).collect(Collectors.toList());
        List<Video> videoList = hBaseResult.getVideoList().stream().filter(e -> e.getVid() != null).map(video -> {
            // 处理author
            resolveField(video, "author");
            // 处理tabs
            String tabs = video.getTabs();
            String newTabs = Arrays.stream(tabs.split(",")).map(tid -> tid.split("-")).filter(parts -> parts.length > 1).map(parts -> parts[1]).collect(Collectors.joining(","));
            video.setTabs(newTabs);
            return video;
        }).collect(Collectors.toList());
        List<UserLog> userLogList = hBaseResult.getUserLogList().stream().filter(e -> e.getId() != null).map(userLog -> {
            resolveField(userLog, "id");
            resolveField(userLog, "uid");
            return userLog;
        }).collect(Collectors.toList());

        return HBaseResult.builder().tabList(tabList).hBaseUserList(hBaseUserList).videoList(videoList).userLogList(userLogList).build();
    }
}

